from django.db.models import Count, Sum

from apps.data.schemas import NumberResponse
from apps.trff.filters import PlanFilter
from apps.trff.models import Plan
from apps.trff.serializers import PlanSerializer
from extensions.common.schema import *
from extensions.common.base import *
from extensions.permissions import *
from extensions.viewsets import *

from apps.common.com import Pagination

class PlanViewSet(ModelViewSet, ExportMixin, ImportMixin):
    """交易计划"""
    serializer_class = PlanSerializer
    permission_classes = [IsAuthenticated]
    pagination_class = Pagination
    filterset_class = PlanFilter
    search_fields = ['number', 'remark']
    ordering_fields = ['id', 'number', 'create_time']
    select_related_fields = ['creator','team']
    queryset = Plan.objects.all()

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        statistic = queryset.aggregate(
            count=Count('id'),
        )

        # 在序列化数据之前进行分页
        page_queryset  = self.paginate_queryset(queryset)
        if page_queryset  is not None:
            serializer = self.get_serializer(page_queryset, many=True)
            print(len(serializer.data))
            data = {
                "count": statistic['count'],
                "results": serializer.data
            }

            return Response(data=data, status=status.HTTP_200_OK)

        # 如果没有分页，则直接序列化所有数据
        serializer = self.get_serializer(queryset, many=True)
        data = {
            "count": statistic['count'],
            "results": serializer.data
        }

        return Response(data=data, status=status.HTTP_200_OK)

    @extend_schema(responses={200: NumberResponse})
    @action(detail=False, methods=['get'])
    def number(self, request, *args, **kwargs):
        """获取编号"""
        number = Plan.get_number(self.team)
        return Response(data={'number': number}, status=status.HTTP_200_OK)

    @transaction.atomic
    @extend_schema(request=None, responses={200: PlanSerializer})
    @action(detail=True, methods=['post'])
    def void(self, request, *args, **kwargs):
        """作废"""
        old_account = self.get_object()
        old_account.is_void = True
        old_account.save(update_fields=['is_void'])
        serializer = PlanSerializer(instance=old_account)
        return Response(data=serializer.data, status=status.HTTP_200_OK)
